package com.xpec.c4.game.login;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.ms.game.db.dto.DataTransfer;
import com.ms.player.Player;
import com.ms.player.PlayerUserType;
import com.ms.service.gmtool.log.PlayerLoginLogModel;
import com.ms.service.module.account.Account;
import com.ms.service.module.account.message.SCharacterLoginNotify;
import com.ms.service.module.broadcastlistener.LoginLogoutListener;
import com.ms.service.module.zone.BasicZone;
import com.ms.service.module.zone.message.SSimplePlayer;
import com.ms.service.module.zone.module.BasicZoneModule;
import com.xpec.c4.db.model.PendingSwitchZoneInfo;
import com.xpec.c4.game.common.LoginVerifyCodeManager;
import com.xpec.c4.game.common.LoginVerifyInfo;
import com.xpec.c4.game.common.VerifyInfoNotifyMsg;
import com.xpec.c4.game.utility.GUID;
import com.xpec.c4.message.login.SAccountCharacterLoginResponse;
import com.xpec.c4.service.contexts.Contexts;
import com.xpec.c4.service.module.BasicServiceModule;
import com.xpec.c4.service.module.ConsistentGroupName;
import com.xpec.c4.service.module.ModuleServer;
import com.xpec.c4.service.module.ServerProperties;
import com.xpec.c4.service.module.common.PlayerCommonInfoManager;

/***
 * 由於login 目前分成兩塊(zone login , login module login , 所以先把邏輯給獨立出來)
 * @author wuweijun
 *
 */
public class CharacterLoginProcLogic {
	
	/**
	 * 
	 */
	private static final Log log = LogFactory.getLog(CharacterLoginProcLogic.class);
	
	/**
	 * 登入並傳送Verify
	 */
	static public void characterLoginCreateCSProc(Account account,
			Player player, GUID sessionID, BasicServiceModule module) {

		String loginModule = ConsistentGroupName.lookUpLoginModule(player.getAccountId(), account.isRobot());
		
		boolean isReConnect = (module != null && module.getModuleName().equals(loginModule))? true:false; 
			
		PendingSwitchZoneInfo verifyReuslt = null;
		
		//登入初始化
		BasicZone.onPlayerLoginOnly(module, player, sessionID);
		
		//預設的位置
		verifyReuslt = setSafePlaceForWorstCase(player);
		
		// 創建驗證碼
		LoginVerifyInfo info = LoginVerifyCodeManager.getInstance().createVerifyCode(player.getGuid(), 
				verifyReuslt.getToZoneId(), LoginVerifyCodeManager.CREATE_VERIFYCODE_PUT_LOCAL);	

		if(log.isInfoEnabled() && ServerProperties.isSaveConsoleLog(player.getUserType())){
			log.info(LoginModule.LOGIN_TRACE_LOG_STRING+" send [S_LOGIN_VERIFYCODE_REQUEST] to LOBBY, s: "+sessionID.toString()+" /g: "+player.getGuid().toString());
		}
		
		LoginVerifyCodeManager.getInstance().sendVerifyCodeNotifyMsg(
				VerifyInfoNotifyMsg.VERIFY_TYPE_LOGIN, info,
				module.getModuleName(), sessionID);
		
		//角色登入 log
		PlayerLoginLogModel playerLog = new PlayerLoginLogModel();
		playerLog.setSessionId(sessionID.toString());
		playerLog.setGuid(player.getGuid().toString());
		playerLog.setPlayerName(player.getNameWithNumber());
		playerLog.setAccountId(account.getAccountId().toString());
		playerLog.setAccountNumber(account.getCooperatorAccountId());
		// TODO kevin jb verify
		playerLog.setCooperatorAccountId(player.getCooperatorAccountId());
		playerLog.setVenderId(player.getVenderId());
		playerLog.setSubVenderId(player.getSubVenderId());
		
		
		if(player.getUserType() == PlayerUserType.ROBORT){
			playerLog.setLoginPlatform("Robot_Center");
			playerLog.setVerison(-1);
		}else {
			
			//client登入時的IP
			String clientIP = PlayerCommonInfoManager.getInstance().getClientIpBySessionId(sessionID);
			playerLog.setClientIP(clientIP);
			
			String[] platform = PlayerCommonInfoManager.getInstance().getLoginPlatformBySessionId(sessionID).split(";");
			StringBuilder builder = new StringBuilder();
			builder.append(platform[0]);
			builder.append(";");
			builder.append(platform[1]);
			playerLog.setLoginPlatform(builder.toString());
			try {
				//版本  => ver-XXX
				int	version = Integer.valueOf(platform[2].split("-")[1]);
				playerLog.setVerison(version);
			}catch(Exception e) {
				
			}
		}

		playerLog.setIsLogin(0);
		
		Contexts.getModule().saveDbLog(playerLog);
	}
	
	// 只給login module使用
	static public void onRecvVerfyCodeNotifyResult(LoginVerifyInfo info,
			String moduleName, GUID sessionId) {

		if (info == null) {
			log.error("onRecvVerfyCodeNotifyResult info == null , session:"
					+ sessionId);
			return;
		}
		
		Player player = getPlayer(info.getUserId());
		if(log.isInfoEnabled() && ServerProperties.isSaveConsoleLog(player.getUserType())){
			log.info(LoginModule.LOGIN_TRACE_LOG_STRING+" get Player Detail Data, g: "+player.getGuid().toString());
		}
		BasicServiceModule module = ModuleServer.getInstance().getBasicServiceModule(moduleName);
		if (player == null || module == null) {
			log.error("onRecvVerfyCodeNotifyResult not found player / account info , session:"
					+ sessionId);
			return;
		}
		
		// 更新角色的 zoneid
		player.setZoneId(info.getDestZoneId());

		//資料傳送用格式
		SSimplePlayer sPlayer = DataTransfer.PlayerToSimple(player);
		
		SAccountCharacterLoginResponse responseMsg = new SAccountCharacterLoginResponse();
		responseMsg.setVerifyCode(info.getVerifyCode());
		responseMsg.setSPlayer(sPlayer);

		
		CharacterLogin data = new CharacterLogin();
		data.player = player;
		data.sessionID = sessionId;
		data.responseMsg = responseMsg;
		data.verifyCode = info.getVerifyCode();
		
		((LoginModule)module).characterLoginCallback(data);
	
		if(log.isInfoEnabled() && ServerProperties.isSaveConsoleLog(player.getUserType())){
			log.info("login player:" + player);	
		}
		
	}
	
	static public Player getPlayer(GUID playerID){
		if(Contexts.getModule() instanceof BasicZoneModule){
			return ((BasicZoneModule)Contexts.getModule()).getPlayerDataAgent().getPlayerByGuid(playerID);
		}
		//沒進入到zone 的action目前不支援此種方式
		else if(Contexts.getModule() instanceof LoginModule){
			LoginModule module = (LoginModule)Contexts.getModule();
			
		   Player player =  module.getPlayerFromCache(playerID);
		   //從login module data取出data的player , <br>
		   // 需將 local資料給移除 (理論上login 不暫存玩家資料, )
		   module.removePlayerFromCache(playerID);
		   
			return player;
		}
		else 
			return null;
		//return PlayerManager.getInstance().getPlayer(playerID);
	}
	
	/**
	 * 默认设置一个位置
	 * @param player
	 * @param loginType
	 *
	 */
	static private PendingSwitchZoneInfo setSafePlaceForWorstCase(Player player){
		PendingSwitchZoneInfo result = new PendingSwitchZoneInfo();

		String moduleName = ConsistentGroupName.lookUpGameLobbyModule(player.getGuid(), player.isRobot());
		result.setToZoneId(moduleName);

		log.warn("Player(" + player.getGuid() + " zoneId:" + result.getToZoneId());
		return result;
	}

	/**
	 * 通知所有的 module 角色登入
	 * 
	 * @param player
	 */
	public static void broadcastCharacterLoginNotify(Player player, BasicServiceModule operateModule) {
		if (player == null) {
			return;
		}

		// 填入要送的資料
		SCharacterLoginNotify notify = new SCharacterLoginNotify();
		notify.setSessionId(player.getSessionID());
		notify.setAccountId(player.getAccountId());
		notify.setPlayerId(player.getGuid());
		notify.setPlayerName(player.getNameWithNumber());

		// 廣播
		try {
			LoginLogoutListener.broadcastPlayerLogIn(notify, operateModule);
		} catch (Exception e) {
			if(log.isErrorEnabled()){
				log.error("can't broadcast player login notify!", e);
			}
			return;
		}

		//2017/05/31 改由指定的module接收
//		GroupMessage msg = new GroupMessage();
//		msg.setMessageType(MessageTypes.S_ACCOUNT_CHARACTER_LOGIN_NOTIFY);
//		msg.setMessageContent(notify);
//		MessageAction.sendGroupMessage(msg);
	}
}
